/**
 * 
 */
package pt.mleiria.bo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import pt.mleiria.vo.GuestbookVO;

/**
 * @author root
 *
 */
public class GuestbookBOImpl implements GuestbookBO, InitializingBean {

private DataSource dataSource;
	
	/**
	 * @param dataSource the dataSource to set
	 */
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public void afterPropertiesSet() throws Exception {
		if (dataSource == null)
			throw new BeanCreationException("A datasource é nula!");

	}

	/* (non-Javadoc)
	 * @see pt.mleiria.bo.GuestbookBO#save(pt.mleiria.vo.GuestbookVO)
	 */
	@Override
	public void save(GuestbookVO guestbook) {
		JdbcTemplate jt = new JdbcTemplate(dataSource);
		jt.update("insert into guestBook(name, comment, ip, approved, dateReg) values(?,?,?,?,?)", 
				new Object[]{guestbook.getName(), guestbook.getComment(), guestbook.getIpOrigin(), new String("1"), guestbook.getRegDate()});
		
	}

	/* (non-Javadoc)
	 * @see pt.mleiria.bo.GuestbookBO#getComments()
	 */
	@Override
	public List<GuestbookVO> getComments() {
		JdbcTemplate jt = new JdbcTemplate(dataSource);
		List<GuestbookVO> comments = jt.query(
			    "select name, comment, dateReg from guestBook where approved = '1'",
			    new RowMapper() {

			        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			            GuestbookVO guestbook = new GuestbookVO(rs.getString(1), rs.getString(2),rs.getString(3));
			            return guestbook;
			        }
			    });
		
		return comments;
	}
	
	
	
}
